<?php
namespace backend\controllers;
use Yii;
use yii\web\Controller;
use backend\models\User;
use backend\models\PasswordForm;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\base\ErrorException;
use backend\models\EmailForm;
class HomeController extends Controller{
    public $layout='main2';
    public function actionPasswordChange(){
        if(Yii::$app->request->isPost){
            $model=new EmailForm();
            if(!($model->load(Yii::$app->request->post()) && $model->validate())){
               echo "<script>alert('请填写你正确的邮箱！');location.href='".Url::toRoute('/home/password-change')."'</script>";
            }
            $session = Yii::$app->session;
            $session->set('sign',rand(10000,99999));
            if($this->EmailSend(Yii::$app->request->post('EmailForm')['email'],Yii::$app->user->identity->getId(),md5($session->get('sign')))){
                echo "<script>alert('邮件已发送，请注意查收！');location.href='".Url::toRoute('/home/password-change')."'</script>";
            }
        }
        return $this->render('passwordchange',['id'=>Yii::$app->user->identity->getId(),'model'=>new EmailForm()]);
    }
    public function actionPasswordSave($aa,$bb){
        $session = Yii::$app->session;
        if(Yii::$app->user->identity->getId()==$aa && md5($session->get('sign'))==$bb){
            return $this->render('passwordsave',['data'=>User::findOne(Yii::$app->user->identity->getId()),'model'=>new PasswordForm()]);
        }
         throw new ErrorException('抱歉，您走错了~');
    }
    public function actionPasswordUpdate(){
        $data=Yii::$app->request->post();
        $model=User::findOne($data['id']);
        $model->password_hash = Yii::$app->security->generatePasswordHash($data['PasswordForm']['password']);
        $model->auth_key = Yii::$app->security->generateRandomString();
        if($model->update()){
            Yii::$app->user->logout();
        }
        return $this->redirect(['/site/login']);
    }
    public function EmailSend($email,$aa,$bb){
        $mail= Yii::$app->mailer->compose();
        $mail->setTo($email);
        $mail->setSubject('密码重置');
        $mail->setHtmlBody("您修改密码的地址:".Html::a('http://'.$_SERVER['SERVER_NAME'].Url::toRoute(['/home/password-save','aa'=>$aa,'bb'=>$bb]),'http://'.$_SERVER['SERVER_NAME'].Url::toRoute(['/home/password-save','aa'=>$aa,'bb'=>$bb])));
        if($mail->send())
            return true;
        else
            return false;
    }
}